import axios from 'axios' // 引入axios
import { emitter } from '@/utils/bus.js'
import type { AxiosInstance } from 'axios'

const service:AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 99999
})
let acitveAxios :number = 0
let Timeout : NodeJS.Timeout | null = null

const headers :any = {
  donNotShowLoading: 1,
  Accept: 'application/json',
  'Content-Type': 'application/json',
};


const showLoading = () => {
  acitveAxios++
  if (Timeout) {
    clearTimeout(Timeout)
  }
  Timeout = setTimeout(() => {
    if (acitveAxios > 0) {
      emitter.emit('showLoading')
    }
  }, 400)
}

const closeLoading = () => {
  acitveAxios--
  if (acitveAxios <= 0) {
    clearTimeout(Timeout)
    emitter.emit('closeLoading')
  }
}
// http request 拦截器
service.interceptors.request.use(
  (config) => {
    // 是否需要load
    config.headers = {
      ...headers,
      ...config.headers
    }
    if (!config.headers.donNotShowLoading) {
      showLoading()
    }
    return config
  },
  error => {
    if (!error.config.donNotShowLoading) {
      closeLoading()
    }
    return error
  }
)

// http response 拦截器
service.interceptors.response.use(
  response => {
    console.log('response', response );
    if (!response.config.donNotShowLoading) {
      closeLoading()
    }
    return response
  },
  error => {
    if (!error.config.donNotShowLoading) {
      closeLoading()
    }
    switch (error.response.status) {
      case 500:
        break
      case 404:
        break
    }
    return error
  }
)
export default service


